<?php  
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 
 * 后台菜单管理模型类
 * @author 66diqiu-li
 *
 */
class Admin_Menu_model extends CI_Model {
	
    private $table = '';
    private $table_site = '';

    public function __construct()
    {
        parent::__construct();
        $this->table  = $this->db->dbprefix("admin_menu");
        $this->table_site  = $this->db->dbprefix("admin_menu_site");
    }

	/**
	 * 
	 * 更新数据
	 * @param array $data 数据数组
	 * @param array $where 更新条件 
	 */
	function edit_row($data,$where){
	    if(!empty($where))$this->db->where($where, NULL, FALSE);
	    return $this->db->update($this->table,$data);
	}
	
	/**
	 * 添加数据
	 * @param $data
     * @return bool
	 */
	function add_row($data){
	    if(is_array($data)){
	        if($this->db->insert($this->table,$data)){
	            return $this->db->insert_id();
	        }else{
	            return false;
	        }
	    }
	}
	
	/**
	 * 获取单条记录
     * @param array $where
     * @param string $field
     * @return mixed
	 */
	function get_row($where=array(),$field='*'){
	    if(!empty($field))$this->db->select($field);
	    $query = $this->db->get_where($this->table,$where,1);
	    return $query->row_array();
	}
	
	/**
	 * 删除数据
     * @param array $where
     * @return bool
	 */
	function remove_row($where=array()){
		if(!empty($where)){
		    return $this->db->delete($this->table,$where);
		}
		return false;
	}
	
	/**
	 * 获取所有管理菜单
     * @param array $where
     * @return array
	 */
	function get_list($where=array()){
        //站点配置信息
        $site_data = $this->get_list_site();
        $this->db->select('id,parent_id,name,sort_order,status,app,controller,action,parameter,type');
	    if(!empty($where))$this->db->where($where, NULL, FALSE);
        $this->db->order_by('sort_order', 'ASC');
        $query = $this->db->get($this->table);
        $data = array();
        foreach($query->result_array() as $row){
            $id = $row['id'];
        	$row['url'] = site_url($row['app'].'/'.$row['controller'].'/'.$row['action'].($row['parameter'] ? '?'.$row['parameter'] : ''));

            //匹配站点菜单中的信息....
            if(isset($site_data[$id])){
                if($site_data[$id]['type']==0)continue;
                $row['app'] = $site_data[$id]['app'];
                $row['controller'] = $site_data[$id]['controller'];
                $row['action'] = $site_data[$id]['action'];
                $row['parameter'] = $site_data[$id]['parameter'];
                $row['url'] = site_url($row['app'].'/'.$row['controller'].'/'.$row['action'].($row['parameter'] ? '?'.$row['parameter'] : ''));
            }
            $data[] = $row;
        }        
        return $data;
	}
	
    /**
     * 菜单权限
     * @return array
     */
    public function get_menu_role() {
        //站点配置信息
        $site_data = $this->get_list_site();

        $this->db->select('id,parent_id,name,app,controller,action,type');
        $query = $this->db->get($this->table);
        $data = array();
        foreach($query->result_array() as $row){
            $id = $row['id'];
            //匹配站点菜单中的信息....
            if(isset($site_data[$id])){
                if($site_data[$id]['type']==0)continue;
                $row['app'] = $site_data[$id]['app'];
                $row['controller'] = $site_data[$id]['controller'];
                $row['action'] = $site_data[$id]['action'];
            }
        	$data[$row['id']] = $row;
        }
        return $data;
    }
	
	/**
	 * 
	 * 获取左侧菜单列表
	 */
	function get_left_menu(){
        $this->load->library('mytreeclass');
        $result = $this->get_list(array('status'=>1));
        $_ACCESS_LIST = $this->session->userdata('_ACCESS_LIST');
        if($_ACCESS_LIST!='ALL'){        	
            $_ACCESS_LIST = explode(',',$_ACCESS_LIST);
            foreach($result as $key=>$val){
            	$check_url = $val['app'].'/'.$val['controller'].'/'.$val['action'];
            	if(!in_array($check_url, $_ACCESS_LIST)){
            		unset($result[$key]);
            	}
            }
        }

        $res = array();
        foreach($result as $key=>$val){
            if($val['parent_id']==0){
                $res[$key] = $val;
                $res[$key]['child'] =array();
                unset($result[$key]);
                foreach($result as $k1=>$v1){
                    if($v1['parent_id']==$val['id']){
                        $res[$key]['child'][$k1]=$v1;
                        $res[$key]['child'][$k1]['child'] = array();
                        unset($result[$k1]);
                        foreach($result as $k2=>$v2){
                            if($v2['parent_id']==$v1['id']){
                                array_push($res[$key]['child'][$k1]['child'], $v2);
                                unset($result[$k2]);
                            }
                        }
                    }
                }
            }
        }
       return $res;
	}
	
	/**
	 * 查询该分类是否有子分类
     * @param $parent_id
     * @return bool
	 */
	function is_has_child($parent_id){
	    $this->db->select('id');
	    $query = $this->db->get_where($this->table,array('parent_id'=>$parent_id),1);
	    $row = $query->row();
	    if(isset($row->id)&&$row->id){
	        return true;
	    }else{
	        return false;
	    }
	}
	
    /**
     * 验证是否可以操作的权限
     * @param array $data array('模块','控制器','方法 默认为index')
     * @return bool
     */
    function check_permition($data = array()){
		static $staticrow;
        //模块名称
        $app = $data[1];
        //控制器名称
        $controll_name = $data[2];
        //方法名称
        $action_name = isset($data[3])?$data[3]:'index';
		
        //菜单表
        if(!isset($staticrow[$app.'_'.$controll_name.'_'.$action_name])){
            $this->db->select('name');
            $query = $this->db->get_where($this->table,array('app'=>$app,'controller'=>$controll_name,'action'=>$action_name,'type'=>1),1);
            $row = $query->result();
            $staticrow[$app.'_'.$controll_name.'_'.$action_name] = $row;
        }else{
            $row = $staticrow[$app.'_'.$controll_name.'_'.$action_name];
        }
        if(empty($row)){
            return true;
        }else{
        	
	    	//是否已经登陆
	    	try{
		    	$this->load->model('admin.Adminuser_model');
	    	$this->Adminuser_model->is_login();
	    	}catch (Exception $e){
	    		show_error($e);
	    	}
    	
        	$_ACCESS_LIST = $this->session->userdata('_ACCESS_LIST');
        	if($_ACCESS_LIST=='ALL'){
        	    return true;
        	}else{
                $_ACCESS_LIST = explode(',',$_ACCESS_LIST);
        		$action = $app.'/'.$controll_name.'/'.$action_name;
        		if(in_array($action, $_ACCESS_LIST)){
        			return true;
        		}else{
        			return false;
        		}
        	}
        }
    }
	
    /**
     * 模块安装时进行菜单注册
     * @param array $data 菜单数据
     * @param array $config 模块配置
     * @param string $dbprefix 表前缀
     * @param int $parentid 父菜单ID
     * @return bool
     */
    public function installModuleMenu(array $data, array $config,$dbprefix='', $parentid = 0) {
        if (empty($data) || !is_array($data)) {
            $this->error = '没有数据！';
            return false;
        }
        if (empty($config)) {
            $this->error = '模块配置信息为空！';
            return false;
        }
        
        //安装模块名称
        $moduleName = $config['module'];
        foreach ($data as $rs) {
            if (empty($rs['route'])) {
                $this->error = '菜单信息配置有误，route 不能为空！';
                return false;
            }
            $route = $this->menuRoute($rs['route'],$moduleName);
            $pid = $parentid ? $parentid : ((is_null($rs['parent_id']) || !isset($rs['parent_id'])) ? (int) $defaultMenuParentid : $rs['parent_id']);
            $newData = array_merge(array(
                'name' => $rs['name'],
                'parent_id' => $pid,
                'type' => isset($rs['type']) ? $rs['type'] : 1,
                'status' => isset($rs['status']) ? $rs['status'] : 0,
                'remark' => isset($rs['remark']) ? $rs['remark'] : '',
                'sort_order' => isset($rs['sort_order'])? (int)$rs['sort_order'] : '50',
                    ), $route);
                    
            if($dbprefix!='')$table = $dbprefix."admin_menu";
            else $table = $this->table;

            //插入数据成功
            if($this->db->insert($table, $newData)){
                $newId = $this->db->insert_id();
                //是否有子菜单
	            if (!empty($rs['child'])) {
	                if ($this->installModuleMenu($rs['child'], $config,$dbprefix, $newId) !== true) {
	                    return false;
	                }
	            }
            }
        }
        return true;
    }
    
    /**
     * 把模块安装时，Menu.php中配置的route进行转换
     * @param $route route内容
     * @param $moduleName 安装模块名称
     * @return array
     */
    private function menuRoute($route, $moduleName) {
        $route = explode('/', $route, 3);
        if (count($route) < 3) {
            array_unshift($route, $moduleName);
        }
        $data = array(
            'app' => $route[0],
            'controller' => $route[1],
            'action' => $route[2],
        );
        return $data;
    }
    
    /**
     * 卸载菜单项
     * @param string $moduleName
     * @return bool
     */
    public function uninstallMenu($moduleName = '') {
        if (empty($moduleName)) {
            if ($this->moduleName) {
                $moduleName = $this->moduleName;
            } else {
                $this->error = '模块名称不能为空！';
                return false;
            }
        }
        $table = $this->db->dbprefix("admin_menu");
        $this->db->delete($table, array('app' => $moduleName));
        return true;
    }
    
    /**
     * 获取站点的菜单配置信息
     * @param array $where 查询条件
     * @return array
     */
    public function get_list_site($where=array()){
        $this->db->select('menu_id,type,app,controller,action,parameter');
        if(!empty($where))$this->db->where($where, NULL, FALSE);
        $query = $this->db->get($this->table_site);
        $data = array();
        foreach($query->result_array() as $row){
            $data[$row['menu_id']] = $row;
        }
        return $data;
    }
}